package site.kitcheng.springboottest.test;

/**
 * ClassName: RSAEncryptWithSalt
 * Package: site.kitcheng.springboottest.test
 * Description:
 *
 * @Author jiangCheng
 * @Create 2025/2/24 11:01
 * @Version 1.0
 */
import javax.crypto.Cipher;
import java.security.*;
import java.util.Base64;
import java.security.SecureRandom;

public class RSAEncryptWithSalt {

    // 生成盐值
    public static String generateSalt() {
        SecureRandom secureRandom = new SecureRandom();
        byte[] salt = new byte[16];  // 16字节的盐值
        secureRandom.nextBytes(salt);
        return Base64.getEncoder().encodeToString(salt);
    }

    // 使用RSA公钥加密，并附加盐值
    public static String encryptWithSalt(String data, PublicKey publicKey) throws Exception {
        // 生成盐值
        String salt = generateSalt();

        // 拼接盐值和数据
        String dataWithSalt = salt + data;

        // 使用RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(dataWithSalt.getBytes());

        // 返回盐值和加密后的数据
        String encryptedString = Base64.getEncoder().encodeToString(encryptedData);
        return salt + ":" + encryptedString;
    }

    public static void main(String[] args) throws Exception {
        // 生成RSA密钥对
        KeyPair keyPair = KeyPairGeneratorUtil.generateKeyPair();
        String s = Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded());
        System.out.println("s = " + s);



        PublicKey publicKey = keyPair.getPublic();
        String s2 = Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());
        System.out.println("s2 = " + s2);

        // 明文数据
        String data = "1234567dfhgfdgsg";

        // 使用公钥加密
        String encryptedData = encryptWithSalt(data, publicKey);

        System.out.println("Encrypted Data with Salt: " + encryptedData);
    }
}
